﻿using Nova_BLL;
using Nova_Common.Extend;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WMS_Api.Areas.WCSSystem.Models;
using WMS_Api.Controllers;
using WMS_Api.Models;
using Swashbuckle.Swagger.Annotations;
using WMS_Api.App_Start;
using Nova_MOD;
using log4net;

namespace WMS_Api.Areas.WCSSystem.Controllers
{
    /// <summary>
    /// WCS 任务功能
    /// </summary>
    [RoutePrefix("api/WCSSystem/Task")]
    [ControllerGroup("WCS", "同步任务功能接口")]
    public class TaskController : BaseApiController
    {
        WcsSysBll WcsBll = new WcsSysBll();
        TCommandBll CmdBll = new TCommandBll();
        TRelationsBll RelationBll = new TRelationsBll();
        ILog _logger = LogManager.GetLogger(typeof(TaskController));

        /// <summary>
        /// 同步WCS任务状态
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("SyncStatus")]

        public ApiResult SyncStatus(TaskStatusModel param)
        {
            _logger.InfoFormat("WCS同步任务,请求参数:{0}", param.ToJson());
            if (param.WmsTaskId.IsEmpty())
                return Error(ResultCode.Error, "WmsTaskId不能为空");
            var cmdEntity = CmdBll.GetEntityByTaskId(int.Parse(param.WmsTaskId));
            if (cmdEntity.IsEmpty())
                return Error(ResultCode.Error, "此任务号不存在于任务表中");
            switch (param.TaskState)
            {
                case (int)TaskStateEnum.Execute:
                    return Execute(cmdEntity, param);
                case (int)TaskStateEnum.Complete:
                    return Complete(cmdEntity, param);
                case (int)TaskStateEnum.Cancel:
                    return Cancel(cmdEntity, param);
                default:
                    return Error(ResultCode.Error, "任务状态不在(2,3,-1)中");
            }
        }

        private ApiResult Execute(TCommands cmdEntity, TaskStatusModel param)
        {
            cmdEntity.TaskStatus = param.TaskState;
            cmdEntity.WriteToPLC = 1;
            cmdEntity.CDT = param.Time;
            bool isUpdate = CmdBll.UpdateEntity(cmdEntity);
            return isUpdate ? Success("同步任务执行状态成功") : Error(ResultCode.Error, "同步任务执行状态失败");
        }

        private ApiResult Complete(TCommands cmdEntity, TaskStatusModel param)
        {
            StoreProceResult res = WcsBll.UpdateCmdState(cmdEntity.TaskID, 1, param.ByWay);
            if (res.ResNo == 1)
            {
                return Success("同步任务状态完成成功");
            }
            else
                return Error(res.ResMsg);
        }

        private ApiResult Cancel(TCommands cmdEntity, TaskStatusModel param)
        {
            StoreProceResult res = WcsBll.UpdateCmdState(cmdEntity.TaskID, 2, param.ByWay);
            if (res.ResNo == 1)
                return Success("同步取消任务成功");
            else
                return Error(res.ResMsg);
        }

        /// <summary>
        ///  WCS读码器申请入库
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost, Route("ApplyPut")]
        public ApiResult ApplyPut(TaskApplyPutModel param)
        {
            _logger.InfoFormat("WCS申请读码入库，请求参数:{0}", param.ToJson());
            if (param.ConveyorDeviceCode.IsEmpty())
                return Error(ResultCode.Error, "ConveyorDeviceCode不能为空");
            if (param.TrayCode.IsEmpty())
                return Error(ResultCode.Error, "TrayCode不能为空");

            // 计算入库分配货位，生成入库指令
            StoreProceResult res = WcsBll.GenternatePutCmd(param.TrayCode, int.Parse(param.ConveyorDeviceCode), 0, 0);
            if (res.ResNo == 1)
                return Success("入库任务生成成功");
            else
                return Error(res.ResMsg);
        }

        /// <summary>
        /// 双伸位WCS申请移库
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost, Route("ApplyMove")]
        public ApiResult ApplyMove(TaskApplyMoveModel param)
        {
            if (param.PositionS.IsEmpty())
                return Error(ResultCode.Error, "PositionS不能为空");
            if (param.TrayCode.IsEmpty())
                return Error(ResultCode.Error, "TrayCode不能为空");

            int lane = int.Parse(param.PositionS.Substring(2, 2));
            int rows = int.Parse(param.PositionS.Substring(4, 1));
            int cols = int.Parse(param.PositionS.Substring(5, 3));
            int layers = int.Parse(param.PositionS.Substring(8, 2));
            StoreProceResult res = WcsBll.GenternateMoveCmd(lane, rows, cols, layers);
            if (res.ResNo == 1)
                return Success("申请移库成功!");
            else
                return Error(res.ResMsg);
        }
    }

}
